package com.example.demo.service.Impl;

import com.example.demo.ao.CensusDataAo;
import com.example.demo.mapper.MoreImageMapper;
import com.example.demo.service.CensusDataService;
import com.example.demo.utils.ImageMergeUtil;
import com.example.demo.vo.BlobImageBase64;
import com.example.demo.vo.CensusDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

@Service
public class CensusDataServiceImpl implements CensusDataService {


    @Autowired
    private MoreImageMapper moreImageMapper;


    @Override
    public List<CensusDataVo> censusData(CensusDataAo censusDataAo) {
        // 1. 获取所有普查数据
        List<CensusDataVo> dataList = moreImageMapper.censusData(censusDataAo);

        // 2. 收集所有图片ID（不去重）
        List<Integer> allImageIds = new ArrayList<>();
        for (CensusDataVo vo : dataList) {
            // 收集所有图片ID字段
            addImageIds(allImageIds, vo.getLocationImg());
            addImageIds(allImageIds, vo.getDeviceTypeImg());
            addImageIds(allImageIds, vo.getManuImg());
            addImageIds(allImageIds, vo.getInstantaneousImg());
            addImageIds(allImageIds, vo.getOvercurrentImg());
            addImageIds(allImageIds, vo.getLimitedImg());
            addImageIds(allImageIds, vo.getZeroSeqImg());
            addImageIds(allImageIds, vo.getPostAccFixedCurImg());
            addImageIds(allImageIds, vo.getPostAccFixedTimeImg());
            addImageIds(allImageIds, vo.getCabinetProImg());
            addImageIds(allImageIds, vo.getProtectionImg());
            addImageIds(allImageIds, vo.getVoManuImage());
            addImageIds(allImageIds, vo.getVoInstantaneousImage());
            addImageIds(allImageIds, vo.getVoOvercurrentImage());
            addImageIds(allImageIds, vo.getVoLimited());
            addImageIds(allImageIds, vo.getVoZeroSeqImage());
            addImageIds(allImageIds, vo.getVoRearAccelerationImage());
            addImageIds(allImageIds, vo.getVoRearAccelerationTimeImage());
            addImageIds(allImageIds, vo.getBasImage());
            addImageIds(allImageIds, vo.getParentImage());
            addImageIds(allImageIds, vo.getLineInOneImage());
            addImageIds(allImageIds, vo.getLineInTwoImage());
        }

        // 3. 批量查询所有图片Base64数据
        Map<Integer, String> imageBase64Map = new HashMap<>();
        if (!allImageIds.isEmpty()) {
            List<BlobImageBase64> base64List = moreImageMapper.getBase64ImagesByIds(allImageIds);
            for (BlobImageBase64 item : base64List) {
                imageBase64Map.put(item.getId(), item.getImageBase64());
            }
        }

        // 4. 处理每条记录，合并图片并设置到对应字段
        for (CensusDataVo vo : dataList) {
            // 位置图片
            processImageField(vo.getLocationImg(), imageBase64Map,
                    vo::setLocationImageList, vo::setLocationImageData);

            // 分界点图片
            processImageField(vo.getDeviceTypeImg(), imageBase64Map,
                    vo::setDeviceTypeImageList, vo::setDeviceTypeImageData);

            // 装置图片
            processImageField(vo.getManuImg(), imageBase64Map,
                    vo::setManuImageList, vo::setManuImageData);

            // 速断图片
            processImageField(vo.getInstantaneousImg(), imageBase64Map,
                    vo::setInstantaneousImageList, vo::setInstantaneousImageData);

            // 过流图片
            processImageField(vo.getOvercurrentImg(), imageBase64Map,
                    vo::setOvercurrentImageList, vo::setOvercurrentImageData);

            // 限时速断图片
            processImageField(vo.getLimitedImg(), imageBase64Map,
                    vo::setLimitedImageList, vo::setLimitedImageData);

            // 零序图片
            processImageField(vo.getZeroSeqImg(), imageBase64Map,
                    vo::setZeroSeqImageList, vo::setZeroSeqImageData);

            // 后加速电流图片
            processImageField(vo.getPostAccFixedCurImg(), imageBase64Map,
                    vo::setPostAccFixedCurImageList, vo::setPostAccFixedCurImageData);

            // 后加速时间图片
            processImageField(vo.getPostAccFixedTimeImg(), imageBase64Map,
                    vo::setPostAccFixedTimeImageList, vo::setPostAccFixedTimeImageData);

            // 进线柜图片
            processImageField(vo.getCabinetProImg(), imageBase64Map,
                    vo::setCabinetProImageList, vo::setCabinetProImageData);

            // 保护图片
            processImageField(vo.getProtectionImg(), imageBase64Map,
                    vo::setProtectionImageList, vo::setProtectionImageData);

            // 装置图片 (高压)
            processImageField(vo.getVoManuImage(), imageBase64Map,
                    vo::setVoManuImageList, vo::setVoManuImageData);

            // 速断图片 (高压)
            processImageField(vo.getVoInstantaneousImage(), imageBase64Map,
                    vo::setVoInstantaneousImageList, vo::setVoInstantaneousImageData);

            // 过流图片 (高压)
            processImageField(vo.getVoOvercurrentImage(), imageBase64Map,
                    vo::setVoOvercurrentImageList, vo::setVoOvercurrentImageData);

            // 限时速断图片 (高压)
            processImageField(vo.getVoLimited(), imageBase64Map,
                    vo::setVoLimitedImageList, vo::setVoLimitedImageData);

            // 零序图片 (高压)
            processImageField(vo.getVoZeroSeqImage(), imageBase64Map,
                    vo::setVoZeroSeqImageList, vo::setVoZeroSeqImageData);

            // 后加速图片 (高压)
            processImageField(vo.getVoRearAccelerationImage(), imageBase64Map,
                    vo::setVoRearAccelerationImageList, vo::setVoRearAccelerationImageData);

            // 后加速时间图片 (高压)
            processImageField(vo.getVoRearAccelerationTimeImage(), imageBase64Map,
                    vo::setVoRearAccelerationTimeImageList, vo::setVoRearAccelerationTimeImageData);

            // 备自投装置图片
            processImageField(vo.getBasImage(), imageBase64Map,
                    vo::setBasImageList, vo::setBasImageData);

            // 母联图片
            processImageField(vo.getParentImage(), imageBase64Map,
                    vo::setParentImageList, vo::setParentImageData);

            // 进线1图片
            processImageField(vo.getLineInOneImage(), imageBase64Map,
                    vo::setLineInOneImageList, vo::setLineInOneImageData);

            // 进线2图片
            processImageField(vo.getLineInTwoImage(), imageBase64Map,
                    vo::setLineInTwoImageList, vo::setLineInTwoImageData);
        }

        return dataList;
    }

    // 辅助方法：添加图片ID到集合
    private void addImageIds(List<Integer> allImageIds, String imgIds) {
        if (imgIds != null && !imgIds.isEmpty()) {
            String[] ids = imgIds.split(",");
            for (String id : ids) {
                try {
                    allImageIds.add(Integer.parseInt(id.trim()));
                } catch (NumberFormatException e) {
                    // 忽略无效ID
                }
            }
        }
    }

    // 辅助方法：处理单个图片字段
    private void processImageField(String imgIds, Map<Integer, String> imageBase64Map,
                                   Consumer<List<String>> setImageList, Consumer<byte[]> setImageData) {
        if (imgIds == null || imgIds.isEmpty()) {
            return;
        }

        List<String> base64List = new ArrayList<>();
        String[] ids = imgIds.split(",");
        for (String idStr : ids) {
            try {
                int id = Integer.parseInt(idStr.trim());
                String base64 = imageBase64Map.get(id);
                if (base64 != null) {
                    //清理
                    if (base64.startsWith("data:image")) {
                        int commaIndex = base64.indexOf(',');
                        if (commaIndex > 0){
                            base64List.add(base64.substring(commaIndex + 1));
                        }
                    }
                    base64 = base64.replace("\\s", "");
                    base64List.add(base64);
                }
            } catch (NumberFormatException e) {
                // 忽略无效ID
            }
        }

        // 设置到List字段
        setImageList.accept(base64List);

        // 合并图片
        if (!base64List.isEmpty()) {
            try {
                byte[] mergedImage = ImageMergeUtil.mergeImages(base64List);
                setImageData.accept(mergedImage);
            } catch (Exception e) {
                // 记录错误
                setImageData.accept(null);
            }
        }
    }
}
